package jta.atomikos.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @author guo
 */
@Configuration
@Primary
@MapperScan(basePackages = "jta.atomikos.two.mapper",sqlSessionFactoryRef="twoSqlSessionFactory")
public class DataSourceTwoConfig {

    /**
     * 配置数据源
     */
    @Primary
    @Bean(name="twoDatasource")
    @ConfigurationProperties(prefix = "spring.jta.atomikos.datasource.two")
    public DataSource twoDatasource() {
        return new AtomikosDataSourceBean();
    }

    /**
     * 创建SqlSessionFactory
     */
    @Primary
    @Bean(name="twoSqlSessionFactory")
    public SqlSessionFactory twoSqlSessionFactory(@Qualifier("twoDatasource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Primary
    @Bean(name="twoSqlSessionTemplate")
    public SqlSessionTemplate twoSqlSessionTemplate(@Qualifier("twoSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}











